package cn.readjava.controller.manage;

import cn.readjava.bean.Video;
import cn.readjava.bean.VideoCategory;
import cn.readjava.service.VideoCategoryService;
import cn.readjava.service.VideoService;
import cn.readjava.util.ResponseResult;
import cn.readjava.vo.VideoCategoryVo;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/manage/video")
public class ManageVideoController {

    @Resource
    private VideoService videoService;
    @Resource
    private VideoCategoryService videoCategoryService;

    // 删除
    @GetMapping("/delete/{id}")
    @ResponseBody
    public Object delete(@PathVariable Long id) {
        try {
            videoService.delete(id);
            return new ResponseResult(200, "删除成功", null);
        } catch (Exception e) {
            return new ResponseResult(100, "删除失败", null);
        }
    }

    // 预更新
    @GetMapping("/update/{id}")
    public String update(@PathVariable Long id, Model model) {
        Video video = videoService.getOne(id);
        model.addAttribute("video", video);
        List<VideoCategory> videoCategoryList = videoCategoryService.findAll();
        model.addAttribute("videoCategoryList", videoCategoryList);
        return "manage/manage-video-update";
    }

    // 更新
    @PostMapping("/update")
    @ResponseBody
    public Object updateArticle(Video vi) {
        Video video = videoService.save(vi);
        if (video != null) {
            return new ResponseResult(200, "更新成功", video);
        }
        return new ResponseResult(100, "更新失败", null);
    }

    @GetMapping("/list/{id}")
    public String list(@PathVariable Long id, Model model) {
        List<Video> videoList = videoService.findByTypeId(id);
        List<VideoCategory> videoCategoryList = videoCategoryService.findAll();
        List<VideoCategoryVo> videoCategoryVoList = new ArrayList<>();
        for (Video video : videoList) {
            for (VideoCategory vc : videoCategoryList) {
                if (video.getVideoTypeId() == vc.getVcId()) {
                    videoCategoryVoList.add(new VideoCategoryVo(video, vc));
                }
            }
        }
        model.addAttribute("videoCategoryVoList", videoCategoryVoList);
        return "manage/manage-video";
    }
}
